package gen.tools.chkin;

import gen.tools.Widgets;
import gen.tools.structures.ChkInFiles;
import gen.tools.structures.ChkInObj;
import gen.tools.structures.ChkInRecord;
import gen.tools.structures.I1S1;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class CreateChkInRecord extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CreateChkInRecord() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	@SuppressWarnings("resource")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final String empId = request.getParameter("empId");				//員工ID
	    final ChkInRecord cirj = new Gson().fromJson( request.getParameter("chkInRecordJson"), ChkInRecord.class);
	    
		String strSQL;
		String res ="Done";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			conn.setAutoCommit(false);	//為取得序號，先將提交關閉
			
			/****建立LOG，第一步就開始記錄程式的執行****/
			strSQL="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, 11);
			ps.setString(2, empId);
			ps.setTimestamp(3, wid.cDT());
			ps.execute();
			strSQL="SELECT MAX(changeLogId) FROM changelog";
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			final int chkInChangLogId = rs.getInt(1);
			
			/****新增繳交主檔****/	
			strSQL="INSERT INTO chkinmain (subsysId,chkInStatusId,isUrgent,isDailyBuild,svnMRurl,svnOLurl,svnMRusr,svnOLusr,svnMRver,svnOLver,creatorId,cDT) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, cirj.getSubsysId() );
			ps.setInt(2, 0);									//繳交記錄狀態
			ps.setString(3, cirj.isUrgent()?"t":"f");			//是否為緊急上線
			ps.setString(4, cirj.isDailyBuild()?"t":"f" );		//是否為每日建置
			ps.setString(5, cirj.getSvnMRurl() );				//SVN MR位址			
			ps.setString(6, cirj.getSvnOLurl() );				//SVN OL位址
			ps.setString(7, cirj.getSvnMRusr() );				//SVN MR帳號
			ps.setString(8, cirj.getSvnOLusr() );				//SVN OL帳號
			ps.setInt(9, cirj.getSvnMRver() );					//SVN MR版次
			ps.setInt(10, cirj.getSvnOLver() );					//SVN OL版次
			ps.setString(11, empId );							//提交人員
			ps.setTimestamp(12, wid.cDT() );					//提交時間
			ps.execute();
			conn.commit();
			strSQL="SELECT MAX(chkInMainId) FROM chkinmain";
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			final int chkInId = rs.getInt(1);
			conn.commit();
			conn.setAutoCommit(true);
			
			for(int i=0;i<cirj.getCios().size();i++){	//一個個的模組
				//開始寫入【繳交模組記錄】
				
				final ChkInObj modObj = cirj.getCios().get(i);				//此模組的繳交結構
				final ArrayList<ChkInFiles> mfo = modObj.getChkInfiles();	//繳交模組檔案所包含的檔案
				final ArrayList<I1S1> mcr = modObj.getCommonReqs();			//繳交模組檔案所共同包含的需求
				final String modId = modObj.getModId();
				
				strSQL="INSERT INTO chkinmod (chkInMainId,modId) VALUES (?,?)";
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, chkInId);
				ps.setString(2, modId );
				ps.execute();
				
				//處理該模組共同的需求
				for( int j=0; j < mcr.size(); j++ ) {
					final int reqId = mcr.get(j).getI1();	//需求ID
					
					strSQL = "INSERT INTO mpchkinmodcomreq (chkInMainId,modId,reqId) VALUES (?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, chkInId);
					ps.setString(2, modId );
					ps.setInt(3, reqId);
					ps.execute();
				}
				
				//處理該模組所繳交的程式
				for( int j=0; j < mfo.size(); j++ ) {
					final ChkInFiles detailObj = mfo.get(j);
					final int detailId = detailObj.getChkInDetailId();			//繳交記錄模組內細項
					final boolean isMR = detailObj.isMR();						//從MR來
					final String fileName = detailObj.getFileName();			//程式名稱
					final String relativePath = detailObj.getRelativePath();	//相對路徑
					final int fileVer = detailObj.getFileVer();					//程式版次
					final ArrayList<I1S1> indviReqs = detailObj.getIndviReqs();	//個別檔案所包含的需求
					
					strSQL="INSERT INTO chkInModDetail (chkInMainId,modId,chkInDetailId,isMR,fileName,relativePath,fileVer) VALUES (?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, chkInId);
					ps.setString(2, modId );
					ps.setInt(3, detailId);
					ps.setString(4, isMR?"t":"f");
					ps.setString(5, fileName);
					ps.setString(6, relativePath);
					ps.setInt(7, fileVer);
					ps.execute();
					
					for( int k=0; k<indviReqs.size(); k++ ) {
						final int reqId = indviReqs.get(k).getI1();	//需求ID
						
						strSQL = "INSERT INTO mpChkInModDetailReq (chkInMainId,modId,chkInDetailId,reqId) VALUES (?,?,?,?)";
						ps = conn.prepareStatement(strSQL);
						ps.setInt(1, chkInId);
						ps.setString(2, modId );
						ps.setInt(3, detailId);
						ps.setInt(4, reqId);
						ps.execute();
					}
				}
			}
			

			/****產生待辦事項****/
			strSQL="INSERT INTO todolist (subsysId,dataType,masterId,roleId,cDT,creatorId) VALUES (?,?,?,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, cirj.getSubsysId());
			ps.setInt(2, 2);				//主檔類型，1表示這個ID是來自變更申請
			ps.setString(3, String.valueOf(chkInId) );			//主檔ID
			ps.setInt(4, 4);				//角色ID
			ps.setTimestamp(5, wid.cDT());
			ps.setString(6, empId);
			ps.execute();
			
			/****將這筆變更申請目前的進度給修改****/
			//改變繳交的狀態  ==> 1 待審
			int chkInStatusId = 1;
			wid.updateCHKINstatus(chkInId, chkInStatusId);
			
			/****完成這次的異動****/
			strSQL = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
			ps = conn.prepareStatement(strSQL);
			ps.setTimestamp(1, wid.cDT());
			ps.setInt(2, chkInChangLogId );
			ps.execute();
		
		} catch(Exception e) {
			res = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	    
	    response.getWriter().write( res );
	}
}
